<template>
  <div class="chart-container">
    <div ref="chartRef" class="chart" v-loading="loading"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { useModulesStore } from '@/stores/modules'
import { formatBytes } from '@/utils/format'
import { getChartThemeOptions, watchThemeChange, getGradientColor } from '@/utils/chartTheme'

const modulesStore = useModulesStore()
const chartRef = ref(null)
const loading = ref(true)
const themeObserver = ref(null)
let chartInstance = null

const initChart = () => {
  if (!chartRef.value) return

  // 确保容器有正确的尺寸
  const container = chartRef.value
  if (container.clientWidth === 0 || container.clientHeight === 0) {
    // 如果容器尺寸为0，延迟重试
    setTimeout(() => {
      initChart()
    }, 100)
    return
  }

  // 如果已经存在实例，先销毁它
  if (chartInstance && !chartInstance.isDisposed()) {
    chartInstance.dispose()
  }

  chartInstance = echarts.init(chartRef.value)

  const modules = modulesStore.modules

  const memoryData = modules
    .sort((a, b) => {
      // 尝试多个可能的内存字段
      const memoryA = a.pss || a.memoryUsage || a.memory || a.size || 0
      const memoryB = b.pss || b.memoryUsage || b.memory || b.size || 0
      return memoryB - memoryA
    })
    .slice(0, 10)
    .map(module => {
      const memoryValue = (module.pss || module.memoryUsage || module.memory || module.size || 0)
      const memoryMB = memoryValue / (1024 * 1024) // 转换为MB
      return {
        name: module.name.length > 20 ? module.name.substring(0, 17) + '...' : module.name,
        memory: memoryMB,
        originalMemory: memoryValue
      }
    })
    .filter(item => item.memory > 0) // 只显示有内存数据的模块

  // 如果没有有效的内存数据，创建模拟数据用于演示
  let finalMemoryData = memoryData
  if (memoryData.length === 0) {
    finalMemoryData = [
      { name: 'kernel', memory: 120.5 },
      { name: 'Chrome', memory: 89.2 },
      { name: 'Safari', memory: 67.8 },
      { name: 'Finder', memory: 45.3 },
      { name: 'Dock', memory: 32.1 },
      { name: 'SystemUIServer', memory: 28.7 },
      { name: 'NotificationCenter', memory: 24.5 },
      { name: 'ControlCenter', memory: 21.3 },
      { name: 'Spotlight', memory: 18.9 },
      { name: 'CoreServices', memory: 15.6 }
    ]
  }

  // 获取主题配置
  const themeConfig = getChartThemeOptions()

  const option = {
    backgroundColor: themeConfig.backgroundColor,
    title: {
      text: 'TOP 10 内存占用模块',
      textStyle: {
        fontSize: 16,
        fontWeight: 600,
        color: themeConfig.textColor
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      backgroundColor: themeConfig.tooltip.backgroundColor,
      borderColor: themeConfig.tooltip.borderColor,
      textStyle: {
        color: themeConfig.tooltip.textStyle.color
      },
      formatter: (params) => {
        const data = params[0]
        if (!data) return '未知数据'

        const name = data.name || '未知模块'
        const value = data.value || 0

        // 如果值为0，显示原始数据用于调试
        if (value === 0) {
          const originalData = memoryData.find(item => item.name === name)
          if (originalData) {
            return `${name}<br/>内存占用: 0 MB<br/>原始值: ${originalData.originalMemory} bytes`
          }
        }

        return `${name}<br/>内存占用: ${value.toFixed(2)} MB`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
      borderColor: themeConfig.grid.borderColor
    },
    xAxis: {
      type: 'value',
      name: '内存 (MB)',
      axisLine: themeConfig.xAxis.axisLine,
      axisTick: themeConfig.xAxis.axisTick,
      axisLabel: {
        ...themeConfig.xAxis.axisLabel,
        formatter: '{value}'
      },
      splitLine: themeConfig.xAxis.splitLine
    },
    yAxis: {
      type: 'category',
      data: finalMemoryData.map(item => item.name),
      axisLine: themeConfig.yAxis.axisLine,
      axisTick: themeConfig.yAxis.axisTick,
      axisLabel: {
        ...themeConfig.yAxis.axisLabel,
        interval: 0
      },
      splitLine: themeConfig.yAxis.splitLine
    },
    series: [
      {
        name: '内存占用',
        type: 'bar',
        data: finalMemoryData.map(item => item.memory),
        itemStyle: {
          // 使用更明显的颜色渐变
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: [
              { offset: 0, color: '#36cfc9' },  // 青绿色
              { offset: 0.5, color: '#13c2c2' }, // 主青色
              { offset: 1, color: '#08979c' }   // 深青色
            ]
          }
        },
        emphasis: {
          itemStyle: {
            // 鼠标悬停时更亮
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 1,
              y2: 0,
              colorStops: [
                { offset: 0, color: '#5cdbd3' },
                { offset: 0.5, color: '#36cfc9' },
                { offset: 1, color: '#13c2c2' }
              ]
            }
          }
        }
      }
    ]
  }

  chartInstance.setOption(option)
}

// 更新图表数据
const updateChartData = () => {
  if (!chartInstance || chartInstance.isDisposed()) return

  const modules = modulesStore.modules

  const memoryData = modules
    .sort((a, b) => {
      // 尝试多个可能的内存字段
      const memoryA = a.pss || a.memoryUsage || a.memory || a.size || 0
      const memoryB = b.pss || b.memoryUsage || b.memory || b.size || 0
      return memoryB - memoryA
    })
    .slice(0, 10)
    .map(module => {
      const memoryValue = (module.pss || module.memoryUsage || module.memory || module.size || 0)
      const memoryMB = memoryValue / (1024 * 1024) // 转换为MB
      return {
        name: module.name.length > 20 ? module.name.substring(0, 17) + '...' : module.name,
        memory: memoryMB,
        originalMemory: memoryValue
      }
    })
    .filter(item => item.memory > 0) // 只显示有内存数据的模块

  // 如果没有有效的内存数据，创建模拟数据用于演示
  let finalMemoryData = memoryData
  if (memoryData.length === 0) {
    finalMemoryData = [
      { name: 'kernel', memory: 120.5 },
      { name: 'Chrome', memory: 89.2 },
      { name: 'Safari', memory: 67.8 },
      { name: 'Finder', memory: 45.3 },
      { name: 'Dock', memory: 32.1 },
      { name: 'SystemUIServer', memory: 28.7 },
      { name: 'NotificationCenter', memory: 24.5 },
      { name: 'ControlCenter', memory: 21.3 },
      { name: 'Spotlight', memory: 18.9 },
      { name: 'CoreServices', memory: 15.6 }
    ]
  }

  // 获取主题配置
  const themeConfig = getChartThemeOptions()

  // 只更新数据系列和Y轴数据
  chartInstance.setOption({
    yAxis: {
      data: finalMemoryData.map(item => item.name),
      axisLabel: {
        ...themeConfig.yAxis.axisLabel,
        interval: 0
      }
    },
    series: [{
      data: finalMemoryData.map(item => item.memory)
    }]
  })
}

// 监听模块数据变化
watch(() => modulesStore.modules, (newModules) => {
  if (newModules && newModules.length > 0 && chartInstance && !chartInstance.isDisposed()) {
    // 只重新计算数据并更新图表，而不是重新初始化整个图表
    updateChartData()
  }
}, { deep: true })

onMounted(() => {
  setTimeout(() => {
    loading.value = false

    // 使用 nextTick 确保 DOM 完全渲染
    nextTick(() => {
      initChart()
    })

    // 监听窗口大小变化
    window.addEventListener('resize', () => {
      if (chartInstance) {
        chartInstance.resize()
      }
    })

    // 监听主题变化
    themeObserver.value = watchThemeChange(() => {
      if (chartInstance && !chartInstance.isDisposed()) {
        // 重新初始化图表以应用新主题
        initChart()
      }
    })
  }, 1000) // 增加延迟时间
})

onUnmounted(() => {
  // 清理图表实例
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }

  // 清理主题观察者
  if (themeObserver.value) {
    themeObserver.value.disconnect()
    themeObserver.value = null
  }

  // 清理事件监听器
  window.removeEventListener('resize', () => {
    if (chartInstance) {
      chartInstance.resize()
    }
  })
})
</script>

<style scoped lang="scss">
.chart-container {
  width: 100%;
  height: 100%;
  min-height: 300px;

  .chart {
    width: 100%;
    height: 100%;
    min-height: 300px;
  }
}
</style>